package servlets;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.MockRoomRepo;
import model.Room;
import model.RoomRepo;
import model.Round;
import model.User;

/**
 * Servlet implementation class RoomServlet
 */
public class RoomServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private RoomRepo room_repo = MockRoomRepo.getInstance();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RoomServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    RequestDispatcher dispacher;
    request.setAttribute("rooms", room_repo.getRooms());
    dispacher = getServletContext().getRequestDispatcher("/rooms.jsp");
    dispacher.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	  RequestDispatcher dispacher;
	  String roomname=null;
	  roomname = (String)request.getParameter("room");
	  Room selected = null;
	  Boolean status = true;

	  if(roomname!=null){
	    try{
	      selected = room_repo.getRoom(roomname);
	    } catch(RuntimeException e){
	      status = false;
	      request.setAttribute("error", e.getMessage());
	    }
	    
	    if(status){
	      if(request.getSession()!=null){
	        User u = (User)request.getSession().getAttribute("loggeduser");
	        if(u!=null){
	          try{
	            selected.addUser(u);
	            
	            if(!selected.hasActiveRound()){
	              Round r = new Round(selected);
	              selected.addRound(r);
	            }
	            request.setAttribute("room", selected);
	          } catch(Exception e){
	            status = false;
	            request.setAttribute("error", e.getMessage());
	          }
	                 
	        } else {
	          status = false;
	          request.setAttribute("error", "You must be logged in to play!");
	        }
	      }
	    }
	    
	  } else {
	    status = false;
      request.setAttribute("error", "Invalid room name");
	  }

	  request.setAttribute("status", status);
    dispacher = getServletContext().getRequestDispatcher("/room.jsp");
    dispacher.forward(request, response);
	}

}
